package com.quanquan.resource.message;

import com.quanquan.resource.service.ImageService;
import com.rabbitmq.client.Channel;
import commond.ImageOutPut;
import exceptions.ImgException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:接收图片信息并绑定图片关系
 *
 * @ClassName: MqImageReceiver
 * @Author: xiaoqianh丶
 * @Date: 2019-03-13 14:07
 * @Version: V1.0
 */
@Slf4j
@Component
public class MqImageReceiver {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ImageService imageService;

    @Autowired
    public MqImageReceiver(ImageService imageService) {
        this.imageService = imageService;
    }


    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "image",
                    durable = "true"),
            exchange = @Exchange(value = "image.exchange",
                    type = "topic"),
            ignoreDeclarationExceptions = "true",
            key = "image.#")})
    @RabbitHandler
    public void updateImageInfo(@Payload ImageOutPut imageOutPut,
                                Channel channel,
                                @Headers Map<String, Object> headers) throws IOException {
        //手工ack
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);

        String foreignKeyId = imageOutPut.getForeignKeyId();
        List<String> imageIds = (List<String>) headers.get("imageIds");
        if (imageIds.size() <= 0) {
            return;
        }
        String imageSource = imageOutPut.getImageSource();

        //先查一下数据库里有没有外建数据，如果有就走更新如果没有就走添加
        boolean result = imageService.queryResult(foreignKeyId);
        try {
            if (!result) {
                /**
                 * 添加关系
                 */
                imageService.bindIngRelationShip(imageIds, foreignKeyId, imageSource);
            } else {
                /**
                 * 修改关系
                 */
                imageService.bindIngRelationShipUpdate(imageIds, foreignKeyId, imageSource);

            }

        } catch (ImgException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }



}
